package erp_services

import (
	"errors"
	"xiehui-service/app/models/erp_models"
	"xiehui-service/global"
)

type orderConsumptionService struct {
}

var OrderConsumptionService = new(orderConsumptionService)

// 获取单条信息
func (orderConsumptionService *orderConsumptionService) GetOneInfo(id uint) (ptOcM *erp_models.OrderConsumption, err error) {
	err = global.App.DB.First(&ptOcM, id).Error
	if err != nil {
		ptOcM = nil
		if err.Error() == "record not found" {
			err = errors.New("数据不存在")
		}
	}
	return
}

func (orderConsumptionService *orderConsumptionService) GetByUnioNo(unionNo string) (ocM erp_models.OrderConsumption, err error) {
	err = global.App.DB.Where("union_no = ? ", unionNo).Find(&ocM).Error

	if err != nil {
		if err.Error() == "record not found" {
			err = errors.New("数据不存在")
		}
	}
	return
}

// 新增信息
func (orderConsumptionService *orderConsumptionService) Create(ocM erp_models.OrderConsumption) (uint, error) {
	result := global.App.DB.Create(&ocM)
	if result.Error != nil {
		return 0, result.Error
	}
	return ocM.ID.ID, nil
}

func (orderConsumptionService *orderConsumptionService) Update(ocM erp_models.OrderConsumption) (err error) {
	if err := global.App.DB.Model(&erp_models.OrderConsumption{}).Where("ID = ?", ocM.ID.ID).Omit("ID", "UnionNo").Updates(&ocM).Error; err != nil {
		return err
	}
	return nil
}

// 根据订单ID更新数据
func (orderConsumptionService *orderConsumptionService) SetById(task_id uint, fields map[string]interface{}) (err error) {
	var ocM erp_models.OrderConsumption
	if err = global.App.DB.First(&ocM, task_id).Error; err != nil {
		err = errors.New("未查询到订单信息")
		return
	}

	if err = global.App.DB.Model(&ocM).Updates(fields).Error; err != nil {
		return
	}

	return nil
}

func (orderConsumptionService *orderConsumptionService) GetByProductionId(id int64, line_number string) (ocM []erp_models.OrderConsumption, err error) {
	err = global.App.DB.Select("material, category, sum(actual_value) as actual_value").Where("production_id = ?  AND line_number = ?", id, line_number).Group("material").Find(&ocM).Error

	if err != nil {
		if err.Error() == "record not found" {
			err = errors.New("数据不存在")
		}
	}
	return
}

// 根据生产单查询盘数
func (orderConsumptionService *orderConsumptionService) GetPanTotalsByProductionId(id int64, line_number string) (totalRecords int64, err error) {
	query := global.App.DB.Model(&erp_models.OrderConsumption{})
	query = query.Where("production_id = ?  AND line_number = ?", id, line_number).Group("plate_no")
	// 获取总记录数
	if err = query.Count(&totalRecords).Error; err != nil {
		return 0, err
	}

	return
}
